<template>
  <div class="app-container">
    <el-container v-loading="changeLoading"
                  element-loading-text="切换租户中..."
                  element-loading-spinner="el-icon-loading">

      <el-header class="filter-container">
        <div>
          <el-row>
            <!--            <el-popover-->
            <!--              placement="top-start"-->
            <!--              width="200"-->
            <!--              title="1"-->
            <!--              trigger="hover"-->
            <!--              content="请选择全部表头后导出">-->
            <el-tooltip class="item" effect="dark" content="请选择全部表头后导出" placement="right-start">
              <el-button type="primary" icon="el-icon-tickets" @click="onExport(0)" class="filter-item">导出当前页

              </el-button>
            </el-tooltip>

            <!--            </el-popover>-->

            <el-button type="primary" icon="el-icon-top-right" @click="onExport(3)" class="filter-item">全部导出
            </el-button>
            <el-button type="primary" icon="el-icon-bottom-left" @click="onImport(0)" class="filter-item">批量导入
            </el-button>
            <!--            <el-button type="primary"  @click="toggleSelection()" class="filter-item">取消选择</el-button>-->

            <el-link type="primary" style="margin-left: 20px;color:blue;" :href="template_excel">下载学生信息模板</el-link>
          </el-row>
          <!--          </div>-->
          <!--          <div class="tool-bar2" style="width: 100%; margin-bottom: 10px">-->
          <el-row>

            <el-popover placement="bottom" trigger="click" style="text-align: center">
              <el-button plain slot="reference" @click="onCheckTitle">
                表头<i class="el-icon-caret-bottom el-icon--right"/>
              </el-button>
              <ul v-if="isShowTitleList" style="list-style-type:none"></ul>

              <ul style="list-style-type:none">
                <li style="margin-bottom: 10px">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="handleCheckAllChange">全选
                  </el-checkbox>
                </li>
                <li v-for="(item,index) in titleList">
                  <el-checkbox v-model="item.checked" :label="item.label" @change="handleCheckedOption"
                               :disabled="isFixTitle(item)"></el-checkbox>
                </li>
              </ul>

              <!--              <el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="handleCheckAllChange">全选 </el-checkbox>-->
              <!--              <el-checkbox-group v-model="checkTitleList" @change="handleCheckedBoxGroup">-->
              <!--                <el-checkbox v-for="(item,index) in titleList" :label="item.label" :key="item.key" v-model="item.label"-->
              <!--                             @change="handleCheckedOption" style="display:block;"></el-checkbox>-->
              <!--              </el-checkbox-group>-->
              <!--              @click="onCheckTitle"-->

              <!--              <el-button plain slot="reference" @click="onCheckTitle">-->
              <!--                表头<i class="el-icon-caret-bottom el-icon&#45;&#45;right"/>-->
              <!--              </el-button>-->


            </el-popover>
            <el-select v-model="condition.organize" placeholder="组织结构" :clearable="true"
                       @clear="()=>{condition.organize=''}" :disabled="isDisable" @change="changeTenant">
              <el-option
                v-for="item in organizeList"
                :key="item.id"
                :label="item.tenantName"
                :value="item.tenantId"
                :disabled="item.active==0">
              </el-option>
            </el-select>
            <el-select v-model="condition.gradeno" placeholder="年级" style="width: 100px" :clearable="true"
                       @clear="()=>{condition.gradeno=''}">
              <el-option
                v-for="item in GRADE"
                :key="item.id"
                :label="item.label"
                :value="item.kcode">
              </el-option>
            </el-select>
            <el-select v-model="condition.classno" placeholder="班级" style="width: 100px" :clearable="true"
                       @clear="()=>{condition.classno=''}">
              <el-option
                v-for="item in CLASS"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>

            <el-select v-model="bind_statue" placeholder="绑定状态" :clearable="true" style="width: 120px"
                       @clear="()=>{condition.bindStatus=-1}">
              <el-option
                v-for="item in BIND_STATUS"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="pay_statue" placeholder="充值状态" :clearable="true" style="width: 120px"
                       @clear="()=>{condition.payStatus=-1}">
              <el-option
                v-for="item in PAY_STATUS"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>

            <el-input v-model="condition.name" placeholder="姓名" style="width: 200px; "></el-input>

            <el-button type="primary" icon="el-icon-search" @click="onSearch()" style="width: 90px;">搜索</el-button>
<!--            <el-button type="primary" icon="el-icon-plus" @click="onCreate(0)" style="margin-left:50px">添加</el-button>-->
            <el-button type="primary" icon="el-icon-plus" @click="onCreate(0)" style="float: right">添加</el-button>

            <!--            <el-cascader-->
            <!--              collapse-tags="true"-->
            <!--              placeholder="展示表头"-->
            <!--              :options="titleList"-->
            <!--              :props="props"-->
            <!--              clearable></el-cascader>-->


            <!--              <el-checkbox-group v-if="isShowTitleList" v-model="checkTitleList">-->
            <!--                <el-checkbox v-for="(item,index) in titleList" :label="item.label"></el-checkbox>-->
            <!--              </el-checkbox-group>-->
            <!--                        <el-transfer v-if="isShowTitleList" v-model="value" :data="titleList"></el-transfer>-->


          </el-row>
          <!--          </div>-->

        </div>


      </el-header>
      <el-main>
        <el-table
          ref="singleTable"
          :data="temperList"
          v-loading="listLoading"
          style="margin-top:40px; "

          highlight-current-row
          :row-class-name="tableRowClassName"
          :header-cell-style="{background:'#e1e4e5',color:'#80878f'}"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            fixed="left">

          </el-table-column>
          <el-table-column align="center" v-for="(item,index) in checkTitleList" :label="item.label" :key="item.key"
                           min-width="80px">
            <!--                           :width="item.width">-->
            <template slot-scope="scope">
              <div style="padding:0;display: block;" v-if="item.label==='头像'">
                <el-popover
                  placement="right"
                  width="390"
                  height="567"
                  trigger="hover"
                >
                  <el-image
                    :src="scope.row.icon"
                  >
                  </el-image>
                  <el-image slot="reference"
                            style="width: 39px; height: 56px"
                            :src="scope.row.icon"
                  >
                  </el-image>
                </el-popover>
              </div>

              <!--              <p v-else-if="item.label==='年级'">{{ scope.row[item.value] }}</p>-->
              <p v-else-if="item.label==='年级'">{{ findObjByProp('kcode', scope.row[item.value], GRADE).label }}</p>
              <p v-else-if="item.label==='班级'">{{ CLASS[parseInt(scope.row[item.value]) - 1].label }}</p>
              <!--              <p v-else-if="item.label==='班级'">{{ scope.row[item.value]}}</p>-->
              <p v-else-if="item.label==='性别'">{{ SEX[parseInt(scope.row[item.value])].label }}</p>

              <el-button v-else-if="item.label==='家长'" size="small" @click="showParentList(scope.row)">预览</el-button>

              <p v-else-if="item.label==='绑定状态'">
                <el-tag
                  :type="BIND_STATUS[scope.row[item.value]].type"
                >
                  {{ BIND_STATUS[scope.row[item.value]].label }}
                </el-tag>
              </p>

              <p v-else-if="item.label==='支付状态'">
                <el-tag
                  :type="PAY_STATUS[scope.row[item.value]].type"
                >
                  {{ PAY_STATUS[scope.row[item.value]].label }}
                </el-tag>
              </p>
              <p v-else-if="item.label==='用户状态'">
                <!--                <el-tag-->
                <!--                  :type="ACTIVE[scope.row[item.value]].type"-->
                <!--                >-->
                <!--                  {{ ACTIVE[scope.row[item.value]].label }}-->
                <!--                </el-tag>-->

                <!--                {{ scope.row.active }}-->
                <el-switch
                  v-model="scope.row.active==1"
                  :width="60"
                  active-text="启用"
                  inactive-text="禁用"
                  :class="switchs"
                  @change="handleModifyStatus(scope.row)"
                >

                </el-switch>

              </p>
              <p v-else-if="item.label==='组织结构'">
                {{
                  findObjByProp('tenantId', scope.row[item.value], organizeList).tenantName
                }}
              </p>
              <p v-else> {{ scope.row[item.value] }}</p>

            </template>
          </el-table-column>


          <el-table-column align="center" label=操作 width="270" fixed="right">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" :type="PAY_STATUS[scope.row.pay_status].type" @click="handlePayStatus(scope.row)">
                {{ PAY_STATUS[scope.row.pay_status].label }}
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row,scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--        <el-pagination-->
        <!--          style="margin-top: 20px"-->
        <!--          @size-change="handleSizeChange"-->
        <!--          @current-change="handleCurrentChange"-->
        <!--          :current-page="1"-->
        <!--          :page-sizes="[50, 60, 70, 80]"-->
        <!--          :page-size="100"-->
        <!--          layout="total, sizes, prev, pager, next, jumper"-->
        <!--          :total="temperList.length">-->
        <!--        </el-pagination>-->

        <pagination v-show="totle >0" :total="totle " :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                    @pagination="refreshTable"/>
        <!--        <pagination v-show="temperListTotle.length>0" :total="temperListTotle.length"  @pagination="getStudents" />-->


        <!--      创建用户面板-->
        <el-dialog

          :title="dialogTitle[dialogType]"
          :visible.sync="dialogVisible"
          :close-on-click-modal=false
          top="5vh">

          <el-form
            ref="studentFrom"
            :model="temper"
            :rules="rules"
            label-width="100px"
            style=" width: 80%; margin-left:50px;">

            <el-form-item label="组织结构：">
              <!--              <el-select v-model="findObjByProp('kcode',temper.gradeno,GRADE).label" placeholder="年级" style="width: 100px">-->
              <el-select v-model="temper.organize" placeholder="学校" prop="name" style="width: 150px"
                         :disabled="isDisable||condition.organize!=''">
                <el-option
                  v-for="(item,index) in organizeList"
                  :key="index"
                  :label="item.tenantName"
                  :value="item.tenantId"
                  :disabled="item.active==0">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="姓名：" prop="name">
              <el-input v-model.trim="temper.name" maxLength="16"></el-input>
            </el-form-item>
            <el-form-item label="学号：" prop="stuno">
              <el-input v-model.trim="temper.stuno" maxlength="3"></el-input>
              <!--                      <span class="underInputWords">字母、数字、下划线</span>-->
            </el-form-item>
            <el-form-item label="学籍号：" prop="educode">
              <el-input v-model.trim="temper.educode" maxlength="25"></el-input>
            </el-form-item>
            <el-form-item label="年级：" prop="gradeno">
              <!--              <el-select v-model="findObjByProp('kcode',temper.gradeno,GRADE).label" placeholder="年级" style="width: 100px">-->
              <el-select v-model="temper.gradeno" placeholder="年级" style="width: 100px">
                <el-option
                  v-for="(item,index) in GRADE"
                  :key="index"
                  :label="item.label"
                  :value="item.kcode">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="班级：" prop="classno">
              <!--              <el-input v-model="temper.classno"></el-input>-->
              <el-select v-model="temper.classno" style="width: 100px">
                <el-option
                  v-for="item in CLASS"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="性别：">
              <el-radio v-model="temper.sex" label="0">男</el-radio>
              <el-radio v-model="temper.sex" label="1">女</el-radio>
            </el-form-item>

            <el-form-item label="身份证：" prop="">
              <el-input v-model="temper.sfz" maxlength="18"></el-input>
            </el-form-item>

            <el-form-item label="电话：" prop="">
              <el-input v-model="temper.tel" maxlength="11"></el-input>
            </el-form-item>

            <el-form-item label="地址：">
              <el-input v-model="temper.address"></el-input>
            </el-form-item>
            <el-form-item label="备注：">
              <!--              <el-input v-model="temper.describe"></el-input>-->
              <el-input type="textarea" v-model="temper.describe"></el-input>
            </el-form-item>

            <el-form-item>
              <div style="text-align:right;">
                <el-button type="danger" @click="cancelDialog('studentFrom')">取消</el-button>
                <el-button type="primary" @click="confirmDialog(dialogType)">确认</el-button>
              </div>
            </el-form-item>
          </el-form>

        </el-dialog>

        <el-dialog
          title="家长列表"
          :visible.sync="isShowParentList"
          top="5vh"
        >
          <el-table
            ref="roleParent"
            :data="parentList"
            highlight-current-row
            width="80%">

            <el-table-column align="center" label="角色">
              <template slot-scope="scope">
                {{ ROLE_PARENTS_NAME[scope.row.parentid].label }}
              </template>
            </el-table-column>

            <el-table-column align="center" label="家长姓名" min-width="100px">
              <!--              <template slot-scope="scope">-->
              <!--                {{ scope.row.name}}-->
              <!--              </template>-->
              <template slot-scope="scope">
                <template v-if="isParentListEdit[scope.$index]">
                  <el-input v-model="scope.row.name"></el-input>
                </template>
                <span v-else>  {{ scope.row.name }}</span>
              </template>

            </el-table-column>

            <el-table-column align="center" label="电话" min-width="200">
              <template slot-scope="scope">

                <template v-if="isParentListEdit[scope.$index]">
                  <el-input v-model="scope.row.tel"></el-input>
                </template>
                <span v-else>  {{ scope.row.tel }}</span>
              </template>
            </el-table-column>

            <el-table-column align="center" label=操作 width="270">
              <template slot-scope="scope">
                <div v-if="!isParentListEdit[scope.$index]">
                  <el-button type="primary" size="small" @click="handleEditRoleParent(scope.row,scope.$index)">编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteRoleParent(scope.row,scope.$index)">解绑
                  </el-button>
                </div>
                <div v-else>
                  <el-button type="primary" size="small" @click="handleSaveRoleParent(scope.row,scope.$index)">保存
                  </el-button>

                </div>


              </template>
            </el-table-column>

          </el-table>

        </el-dialog>

        <!--      批量上传面板-->
        <el-drawer

          :visible.sync="isUpload"
          direction="ttb"
          :before-close="handleCloseUpload"
          size="50%">
          <Uploadexcel
            ref="studentUpload"
            style="text-align: center" :tape-data="temper" :on-success="handleSuccessExcel"
            :upload-path="upload_excel"/>

          <!--          <upload-excel-component style="text-align: center" :tape-data="tapeDateExcel" :on-change="handleSuccessExcel"  />-->
        </el-drawer>


      </el-main>

    </el-container>
  </div>
</template>

<script>
import Link from '@/layout/components/Sidebar/Link'
import switchs from '@/styles/switch.scss'
import {
  addStudent,
  deleteParent, deleteparentdata,
  deleteStudent,
  getParents,
  getStudents, getStudentsByCondition,
  updateParent,
  updateStudent
} from '@/api/student'
import { isInteger } from '@/utils/validate'
import Uploadexcel from '@/components/UploadExcel/index.vue'
import { parseTime } from '@/utils'
import { findObjByProp } from '@/utils/utilc'
import Pagination from '@/components/Pagination'
import { Message } from 'element-ui'
import { mapGetters } from 'vuex'
import { addConsumerHXY, delConsumerHXY, updatePayStatus } from '@/api/hxy' // secondary package based on el-pagination

const defaultCondition = {
  organize: '',
  gradeno: '',
  classno: '',
  name: '',
  bindStatus: -1,//绑定状态
  active: -1,//激活状态
  payStatus: -1//支付状态
}

const defaultTemper = {
  key: '',
  icon: 'https://iptv.zhixue100.com.cn/icon/s.jpg',
  gradeno: '',
  classno: '',
  educode: '',
  name: '',
  sex: '0',
  sfz: '',
  stuno: '',
  tel: '',
  role_parents: [0],
  address: '',
  bind_status: '0',
  bindcode: '',
  pay_status: '0',
  organize: '',

  describe: '',//备注
  active: '1',//激活状态
  dueTime: ''//时效时间

}

const organize = [
  { id: '0', label: '未选择' },
  { id: '1', label: '汉唐和雅' },
  { id: '2', label: '金马小学' },
  { id: '3', label: '高新区试验小学' }
]

const classList = [
  // { id: '0', label: '' },
  { id: '1', label: '1班' },
  { id: '2', label: '2班' },
  { id: '3', label: '3班' },
  { id: '4', label: '4班' },
  { id: '5', label: '5班' },
  { id: '6', label: '6班' },
  { id: '7', label: '7班' },
  { id: '8', label: '8班' },
  { id: '9', label: '9班' },
  { id: '10', label: '10班' },
  { id: '11', label: '11班' },
  { id: '12', label: '12班' },
  { id: '13', label: '13班' },
  { id: '14', label: '14班' },
  { id: '15', label: '15班' },
  { id: '16', label: '16班' },
  { id: '17', label: '17班' },
  { id: '18', label: '18班' },
  { id: '19', label: '19班' },
  { id: '20', label: '20班' },

  { id: '21', label: '20班' },
  { id: '22', label: '22班' },
  { id: '23', label: '23班' },
  { id: '24', label: '24班' },
  { id: '25', label: '25班' },
  { id: '26', label: '26班' },
  { id: '27', label: '27班' },
  { id: '28', label: '28班' },
  { id: '29', label: '29班' },
  { id: '30', label: '30班' },
  { id: '31', label: '31班' },
  { id: '32', label: '32班' },
  { id: '33', label: '33班' },
  { id: '34', label: '34班' },
  { id: '35', label: '35班' },
  { id: '36', label: '36班' },
  { id: '37', label: '37班' },
  { id: '38', label: '38班' },
  { id: '39', label: '39班' },
  { id: '40', label: '40班' },
  { id: '41', label: '41班' },
  { id: '42', label: '42班' },
  { id: '43', label: '43班' },
  { id: '44', label: '44班' },
  { id: '45', label: '45班' },
  { id: '46', label: '46班' },
  { id: '47', label: '47班' },
  { id: '48', label: '48班' },
  { id: '49', label: '49班' },
  { id: '50', label: '50班' }
]
/**
 * 表头可展示项
 * */
const defaultTitleName = [
  { key: 0, value: 'key', label: 'ID', width: 50, checked: true },
  { key: 1, value: 'icon', label: '头像', width: 120, checked: true },
  { key: 2, value: 'name', label: '姓名', width: 120, checked: true, disabled: true },
  { key: 3, value: 'gradeno', label: '年级', width: 100, checked: true, disabled: true },
  { key: 4, value: 'classno', label: '班级', width: 80, checked: true, disabled: true },
  { key: 5, value: 'stuno', label: '学号', width: 80, checked: true, disabled: true },
  { key: 6, value: 'educode', label: '学籍号', width: 129, checked: true, disabled: true },
  { key: 7, value: 'sex', label: '性别', width: 80, checked: true },
  { key: 8, value: 'sfz', label: '身份证', width: 220, checked: true },
  { key: 9, value: 'tel', label: '电话', width: 150, checked: true },
  { key: 10, value: 'role_parents', label: '家长', width: 150, checked: true },
  { key: 11, value: 'bind_status', label: '绑定状态', width: 150, checked: true },
  { key: 12, value: 'bindcode', label: '绑定码', width: 150, checked: true },
  { key: 13, value: 'pay_status', label: '支付状态', width: 150, checked: true },
  { key: 14, value: 'address', label: '地址', width: 220, checked: true },
  { key: 15, value: 'describe', label: '备注', width: 220, checked: false },
  { key: 16, value: 'active', label: '用户状态', width: 120, checked: true },
  { key: 17, value: 'organize', label: '组织结构', width: 220, checked: true }
]

/**
 * 表头固定展示项
 * */
const defaultCheckFixTitle = [
  '姓名',
  '年级',
  '班级',
  '学号',
  '学籍号'
]
/***
 * 家长角色数据对象模型
 * @type {{openid: string, name: string, educode: string, tel: string, id: string, bindcode: string, parentid: string}}
 */
const defaultRoleParentNameModel = {
  id: '-1',
  bindcode: '',
  educode: '',
  name: '',
  parentid: '0',
  tel: '',
  openid: ''
}

export default {
  name: 'students',
  components: { Link, Uploadexcel, Pagination },
  data() {
    return {

      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        educode: [{ required: true, message: '不能为空', trigger: 'blur' }],
        gradeno: [
          { required: true, message: '请选择年级', trigger: 'change' }
        ],
        classno: [{
          required: true, message: '请选择班级', trigger: 'change'
        }, { validator: isInteger, trigger: 'blur' }],
        stuno: [{ required: true, message: '请输入数字', trigger: 'blur' }, { validator: isInteger, trigger: 'blur' }]
      },
      input_toolbar: '',
      isUpload: false,

      isShowTitleList: true,

      dialogTitle: ['创建', '编辑'],
      temper: Object.assign({}, defaultTemper),
      temperList: [],
      temperListTotle: [],
      tableHeader: [],
      roleList: [],
      dialogVisible: false,
      dialogType: '0',
      organize_id: 0,//组织机构id
      organizeList: this.$global.ORGANIZELIST(),//组织机构列表

      titleList: defaultTitleName,
      checkTitleList: defaultTitleName,

      isCheckAll: true,//表头项，全选状态
      isIndeterminate: false,
      //这两个新增参数是在导出学生数据时追加的
      // headerPush:['组织结构','激活状态'],
      // filterValPush:['organize','active'],

      props: { multiple: true, emitPath: false },

      str_tableRowClassName: '',

      // tempGrade: '',
      // tempClass: '',
      // tempOrganize_id: '',
      // bindId: '',
      // payid: '',

      /**
       * 筛选条件
       * */
      condition: defaultCondition,

      parentList: [],
      isParentListEdit: [],
      isShowParentList: false,
      ROLE_PARENTS_NAME: this.$global.ROLE_PARENTS_NAME,

      BIND_STATUS: this.$global.BIND_STATUS,
      PAY_STATUS: this.$global.PAY_STATUS,

      GRADE: [],
      CLASS: classList,
      SEX: this.$global.SEX,
      ACTIVE: this.$global.ACTIVE,

      selectList: '',
      multipleSelection: [],
      downloadLoading: false,
      filename: 'students',//文件名称

      //----excel相关-----------
      uploadfiles: [],
      tapeDateExcel: {//上传excel时用到的部分参数
        actid: '',
        name: '题库',//固定名称
        codename: 'qusbank',//固定名称
        url: '',             //此项未空
        auther: 'cxy',
        excelurl: 'this.pt_type.server',        //excel保存的路径
        modifytime: parseTime(new Date()),
        platform: 'this.platformKey'
      },

      switchs: switchs,
      template_excel: this.$global.TEMPLATE_EXCEL[0],
      upload_excel: this.$global.UPLOAD_EXCEL[0],
      listLoading: false,

      listQuery: {
        page: 1,
        limit: 30
      },
      totle: 0,
      changeLoading: false


      // listQuery: {
      //   importance: undefined,
      //   title: undefined,
      //   type: undefined,
      //   sort: '+id'
      // },

    }

  },

  created() {

    this.checkTitleList = []
    for (let i = 0; i < defaultTitleName.length; i++) {
      if (defaultTitleName[i].checked) {
        this.checkTitleList.push(defaultTitleName[i])
      }
    }

    // this.isDisabled = this.role=='RA0003'?false:true
    // console.log(this.name + ' ' + this.user_organize + ' ' + this.user_routes + ' ' + this.user_role)

    if (this.user_role == 'RA0003') {
      this.condition.organize = this.user_organize
    }
    // this.getStudents()

    this.init()
  },

  computed: {

    currLimit:{

      get(){
        return this.listQuery.limit
      },

      set(val){
        this.listQuery.limit = val
      }
    },

    bind_statue: {
      get() {

        if (this.condition.bindStatus < 0) {
          return ''
        }
        return this.condition.bindStatus
      },
      set(val) {
        this.condition.bindStatus = val
      }
    },

    pay_statue: {
      get() {
        if (this.condition.payStatus < 0) {
          return ''
        }
        return this.condition.payStatus
      },
      set(val) {
        this.condition.payStatus = val
      }
    },

    ...mapGetters([
      'name',
      'avatar',
      'user_organize',
      'user_role',
      'user_routes'
    ]),

    isDisable: {
      get() {
        console.log('组织接口：' + (this.user_role == 'RA0003'))

        return this.user_role == 'RA0003' ? true : false
      },
      set(val) {
      }
    }

  },
  watch: {},

  methods: {

    async init(){
      this.GRADE = await this.$global.GRADE_SYS()
      this.organizeList = await this.$global.ORGANIZELIST()//组织机构列表
    },

    /**
     * 本地数据和服务器数据格式转换
     *
     * @param local 本地数据
     * @param server 服务端数据
     * @param type 转换类型 1 服务端转本地 other：本地转服务端
     *
     *
     * */
    server_data_convert(local, server, type) {

      // for (let serverKey of Object.keys(server)) {
      // }

      //返回的顺序不固定
      // let local_arr = Object.keys(local)
      // let server_arr = Object.keys(server)
      // for (let i = 0; i < server_arr.length; i++) {
      //   local[local_arr[i]] = server[server_arr[i]]
      //   console.log(local_arr[i]+"="+server_arr[i]+"="+server[server_arr[i]])
      // }

      if (type == 1) {
        local.key = server.id ,
          local.icon = server.icon,
          local.bindcode = server.bindcode,
          local.gradeno = server.gradeno ,
          local.classno = server.classno ,
          local.educode = server.educode ,
          local.name = server.name,
          local.sex = server.sex,
          local.sfz = server.sfz ,
          local.stuno = server.stuno,
          local.tel = server.tel ,
          local.roleParents = server.roleParents ,
          local.address = server.address ,
          local.bind_status = server.bindStatus,
          local.pay_status = server.payStatus,
          local.organize = server.organize,
          local.describe = server.description,
          local.active = server.active,
          local.parentidFirst = server.parentidFirst,
          local.dueTime = server.dueTime
      } else {
        server.id = local.key,
          server.icon = local.icon ,
          server.bindcode = local.bindcode  ,
          server.gradeno = local.gradeno ,
          server.classno = local.classno  ,
          server.educode = local.educode ,
          server.name = local.name ,
          server.sex = local.sex  ,
          server.sfz = local.sfz  ,
          server.stuno = local.stuno ,
          server.tel = local.tel ,
          server.roleParents = local.roleParents ,
          server.address = local.address ,
          server.bindStatus = local.bind_status  ,
          server.payStatus = local.pay_status  ,
          server.organize = local.organize  ,
          server.description = local.describe ,
          server.active = local.active  ,
          server.parentidFirst = local.parentidFirst  ,
          server.dueTime = local.dueTime
      }

    },

    showParentList(student) {
      this.getRoleParent(student.bindcode)
      this.isShowParentList = true

    },

    handleEditRoleParent(parent, index) {
      // this.isParentListEdit[index] = true
      this.$set(this.isParentListEdit, index, true)

    },

    /**
     *
     * 解绑家长
     * **/
    async handleDeleteRoleParent(parent, index) {

      // const res = await deleteParent(parent)
      // parent.createTime='2020/03/24'
      // parent.updateTime='2020/03/24'

      const res = await deleteparentdata(parent)
      if (res.code == '20000') {
        this.parentList.splice(index, 1)
      }

    },

    async handleSaveRoleParent(parent, index) {

      const res = await updateParent(parent.id, parent)

      if (res.code == '20000') {
        this.$set(this.isParentListEdit, index, false)
      }

    },

    // toggleSelection(rows) {
    //   if (rows) {
    //     rows.forEach(row => {
    //       this.$refs.multipleTable.toggleRowSelection(row);
    //     });
    //   } else {
    //     this.$refs.multipleTable.clearSelection();
    //   }
    // },

    /**
     * 表头切换
     */
    handleCheckAllChange(val) {
      console.log('handleCheckAllChange==' + val)
      // this.checkTitleList = this.titleList.filter(function(obj, index) {
      //     obj.cheched = this.isCheckAll
      //   return obj.checked
      // })

      this.checkTitleList = []
      for (let index in this.titleList) {
        if (!val) {
          let bool = defaultCheckFixTitle.some((value) => {
            // console.log("value="+value)
            return value == this.titleList[index].label
          })
          if (bool) {
            this.titleList[index].checked = true
            this.checkTitleList.push(this.titleList[index])
          } else {
            this.titleList[index].checked = val
          }

        } else {
          this.titleList[index].checked = val
          this.checkTitleList.push(this.titleList[index])
        }
      }

      // this.checkTitleList = val ? this.titleList : []
      this.isIndeterminate = false

      // if(this.isCheckAll){
      //   for (let item in this.checkTitleList) {
      // item.checked = val
      // console.log("item.checked=="+JSON.stringify(this.checkTitleList))
      // }
      // }

    },

    handleCheckedBoxGroup(value) {

      let checkedCount = value.length
      this.isCheckAll = checkedCount === this.checkTitleList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.checkTitleList.length

      // console.log("check-group onchange =="+JSON.stringify(value))

    },

    isFixTitle(item) {

      let bool = defaultCheckFixTitle.some(function(value) {
        return value == item.label
      })
      return bool
    },

    handleCheckedOption(val) {
      // console.log("handleCheckedOption onchange =="+val)
      this.checkTitleList = this.titleList.filter(function(obj, index) {

        return obj.checked

      })

      let checkedCount = this.checkTitleList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.titleList.length

      // console.log("handleCheckedOption onchange =="+checkedCount+"  ")

    },
    isCheck(val) {
      // if (this.checkTitleList.length > 0) {
      //   let arr = this.checkTitleList
      //   return arr.some(function(obj, index, arr) {
      //
      //     return obj.label == val
      //   })
      // } else {
      //   return false
      // }
// console.log("check-box onchange ")
    },

    onCheckTitle() {
      this.isShowTitleList = this.isShowTitleList ? false : true

      // console.log("item.checked=2="+JSON.stringify(this.checkTitleList))

    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    tableRowClassName({ row, rowIndex }) {
      if (row.active == 0) {
        return this.str_tableRowClassName
      }
      // return 'alive-row';

      // let self = this
      // for(let i=0;i<self.selectList.length;i++) {
      //   console.log("rowIndex="+rowIndex+"   "+self.selectList[i])
      //
      //   if (rowIndex === self.selectList[i]) {
      //     return 'alive-row';
      //   }
      // }
    },

    removetag() {

      console.log('removetag')
    },
    removetagClear() {

      console.log('removetagClear')
    },

    async changeTenant(tenant) {

      // console.log('切换租户：' + tenant)

      if (tenant != null && tenant != '') {
        let tenantName = findObjByProp('tenantId', tenant, this.organizeList).tenantName

        this.changeLoading = true
        await this.$global.CHANGE_TENANT(tenant).then(
          (res) => {
            // console.log('changeTenant=true='+res)
            this.changeLoading = false
            this.condition.organize = tenant
            this.$notify({
              title: 'Success',
              dangerouslyUseHTMLString: true,
              message: '【' + tenantName + '】切换成功!',
              type: 'success',
              duration: 1500

            })
          },
          () => {
            this.condition.organize = ''
            this.changeLoading = false
            this.$notify({
              title: 'Error',
              dangerouslyUseHTMLString: true,
              message: '【' + tenantName + '】切换失败!',
              type: 'error',
              duration: 1500

            })
          }
        ).catch(error => {
          this.condition.organize = ''
          this.changeLoading = false
          this.$notify({
            title: 'Error',
            dangerouslyUseHTMLString: true,
            message: '【' + tenantName + '】切换异常!',
            type: 'error',
            duration: 1500

          })
        })

        this.temperList = []

      }
    },

    onSearch() {
      // if(this.role=="RA0003"){
      //   this.condition.organize = this.organize
      // }
      console.log('搜索：' + this.condition.organize)
      if (this.condition.organize != null && this.condition.organize != '') {

        this.getStudents()

      } else {

        Message({
          message: '组织结构不能为空',
          type: 'error',
          duration: 1000
        })
      }

    },

    onCreate(type) {

      if (this.condition.organize == null || this.condition.organize == '') {
        Message({
          message: '组织结构不能为空',
          type: 'error',
          duration: 1000
        })
        return false
      }
      this.dialogType = 0
      this.dialogVisible = true
      this.$nextTick(() => {
        this.temper = Object.assign({}, defaultTemper)
        // if (this.user_role == 'RA0003') {
        //   this.temper.organize = this.condition.organize
        // }
        this.temper.organize = this.condition.organize

      })

      console.log('onCreate==' + JSON.stringify(this.temper))

    },
    handleCloseUpload(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    },

    handleSuccessExcel({ file, fileList }) {
      // this.temperList = results
      // console.log('student上传Excelfile=' + JSON.stringify(file))
      // console.log('student上传ExcelfileList=' + JSON.stringify(fileList))
      // this.tableHeader = header

      if (file.response.code == '20000') {
        this.getStudents()
      }

    },

    handleChange({ results, header }) {
      // this.temperList = results
      // console.log('student上传Excel=' + JSON.stringify(results[0]))
      this.tableHeader = header
    },

    beforeUploadExcel(file) {
      this.uploadfiles = file
      console.log('this.uploadfiles==' + this.uploadfiles[0])
      const isLt1M = file.size / 1024 / 1024 < 10

      if (isLt1M) {
        return true
      }

      this.$message({
        message: '最大不超过10M',
        type: 'warning'
      })
      return false
    },

    onImport(type) {
      if (this.condition.organize == null || this.condition.organize == '') {
        Message({
          message: '组织结构不能为空',
          type: 'error',
          duration: 1000
        })
      } else {
        this.upload_excel = this.$global.UPLOAD_EXCEL[0] + '/' + this.condition.organize

        console.log('this.upload_excel=' + this.upload_excel)

        this.isUpload = this.isUpload ? false : true
      }

      // this.getHeaderExcel(this.checkTitleList,"label")

    },

    onExport(type) {
      if(type==0){
        if (this.multipleSelection.length) {
          this.downloadLoading = true
          import('@/vendor/Export2Excel').then(excel => {
            // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
            // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
            const tHeader = this.getHeaderExcel(this.checkTitleList, 'label')
            // tHeader.push('激活状态')
            const filterVal = this.getValueExcel(this.checkTitleList, 'value')
            // filterVal.push('active')
            const list = this.multipleSelection
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.filename
            })
            this.$refs.singleTable.clearSelection()
            this.downloadLoading = false
          })
        } else {
          this.$message({
            message: '请选择要导出的数据',
            type: 'warning'
          })
        }
      }


      if(type==3){
        if (this.temperListTotle.length) {
          this.downloadLoading = true
          import('@/vendor/Export2Excel').then(excel => {
            // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
            // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
            const tHeader = this.getHeaderExcel(this.checkTitleList, 'label')
            // tHeader.push('激活状态')
            const filterVal = this.getValueExcel(this.checkTitleList, 'value')
            // filterVal.push('active')
            const list = this.temperListTotle
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.filename
            })
            this.$refs.singleTable.clearSelection()
            this.downloadLoading = false
          })
        } else {
          this.$message({
            message: '请选择要导出的数据',
            type: 'warning'
          })
        }
      }

    },



    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        // console.log("j=="+j+" "+v[j])
        if (j == 'gradeno') {

          return this.$global.GRADE_LOCAL[v[j]]

        } else if (j == 'classno') {
          // v[j]
          return v[j] + '班'
        } else {
          return v[j]
        }

      }))
    },

    handleEdit(item) {
      this.dialogType = 1
      this.dialogVisible = true
      this.temper = item
    },

    handleDelete(item, index) {
      console.log('index==' + index)

      this.$confirm('确定要删除此条信息吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // await deleteStudent(item.bindcode)
        let server = {}
        this.server_data_convert(item, server, 0)
        let {code } = await deleteStudent(server)
        console.log("删除学生结果："+code)
        if(code=='20000'){
          await delConsumerHXY(item.bindcode)
          // console.log("删除学生结果："+JSON.stringify(data))

          // if(data.message=="删除用户成功"){
            this.temperList.splice(index, 1)
            this.totle = --this.totle < 1 ? 0 : this.totle
            this.$message({
              type: 'success',
              message: 'Delete success !'
            })
          // }else{
          //   this.$message({
          //     type: 'error',
          //     message: '删除失败-HXY!'
          //   })
          // }
        }else{
          this.$message({
            type: 'error',
            message: '删除失败 !'
          })
        }



      })
        .catch(err => {
          console.error(err)
        })

    },

    cancelDialog(fromname) {
      this.dialogVisible = false
      this.$refs[fromname].resetFields()
    },

    async confirmDialog(_dialogType) {

      let diaType = this.dialogType

      this.$refs['studentFrom'].validate(async(valid) => {
        if (valid) {

          let server = {}
          this.server_data_convert(this.temper, server, 0)

          if (diaType == 0) {//创建
            // const { data } = await addStudent(server)
            const { data } = await addStudent(server)
            this.temper.key = data.id
            this.temper.bindcode = data.bindcode

            //-----华栖云------------------
            // let role_ids = []
            // let structure_ids = []
            // role_ids.push(await this.$global.getROLE_ID_HXY('RA1002'))
            // structure_ids.push(this.hxy_structure)

            let gradeName = findObjByProp('kcode', this.temper.gradeno, this.GRADE).label

            let role_ids = await this.$global.getROLE_ID_HXY('RA1002')
            let structure_ids = this.hxy_structure

            let hxy_data = {
              role_name: role_ids,
              structure_name: gradeName + this.CLASS[parseInt(this.temper.classno) - 1].label,//
              account: this.temper.bindcode,
              // phone: this.temper.tel + '',
              realname: this.temper.name,
              // password: this.temper.bindcode + this.condition.organize,
              password: this.$global.PWS_STU_TEA,
              bindcode: this.temper.bindcode
              // pay_status: 0,
              // expire: 1,
              // iptv_bindcode: '1'
            }
            let {} = await addConsumerHXY(hxy_data)
            //-----华栖云------------------

            this.temperList.push(this.temper)

          } else {

            console.log('updateStudent==' + JSON.stringify(server))
            await updateStudent(this.temper.key, server)
            for (let index = 0; index < this.temperList.length; index++) {
              if (this.temperList[index].key === this.temper.key) {
                this.temperList.splice(index, 1, Object.assign({}, this.temper))
                break
              }
            }
          }

          this.dialogVisible = false
          console.log('temper=tel=' + this.temper.tel)
        } else {
          console.log('error submit!!')
          return false
        }
      })
      // this.cancelDialog('studentFrom')

    },

    async refreshTable(res){
      // this.listQuery.limit = parseInt(limit)
      // this.listQuery.page = parseInt(page)

      console.log('refreshTable==page=='+res.page+"  limit="+res.limit)

      await this.getStudents()
    },


    async getStudents() {
      // console.log('getStudents==1')

      this.listLoading = true
      // this.GRADE = await this.$global.GRADE_SYS()
      // // console.log('getStudents==2')
      // this.organizeList = await this.$global.ORGANIZELIST()//组织机构列表
      // console.log('this.organizeList==' + JSON.stringify(this.organizeList))
      // console.log('getStudents==3')
      this.temperList = []
      this.temperListTotle = []

      let start = this.listQuery.limit * this.listQuery.page
      let end = this.listQuery.limit * (this.listQuery.page - 1)
      console.log('start=='+start +"--end=="+end)

      //发起网络请求后page和limit会被重置，原因未知
      let clickPage = this.listQuery.page
      let clickLimit = this.listQuery.limit

      if (this.condition.organize != null && this.condition.organize != '') {
        // const res = await
        getStudentsByCondition(this.condition).then(res => {
            // getStudentsByCondition(this.organize_id).then(res=>{
            // console.log('2page==' + this.listQuery.page+" lim="+this.listQuery.limit)
            this.temperList = []
            this.temperListTotle = []
            this.listQuery.page = clickPage
            this.listQuery.limit = clickLimit

            for (let i = 0; i < res.data.length; i++) {
              let temp = Object.assign({}, this.temper)
              this.server_data_convert(temp, res.data[i], 1)
              this.temperListTotle.push(temp)
            }

            this.totle = this.temperListTotle.length

            // console.log('1page==' + end+" lim="+start)

            // this.temperList = this.temperListTotle.filter((item, index) => index < this.limit * this.page && index >= this.limit * (this.page - 1))
            this.temperList = this.temperListTotle.filter((item, index) => index < start && index >= end)

            // console.log('temperList==' + JSON.stringify(this.temperList))

            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)

          },
          () => {
            this.listLoading = false
          }
        )

      } else {
        this.listLoading = false
      }

      // console.log('this.temperList==' + JSON.stringify(this.temperList))
    },

    async getRoleParent(bindcode) {
      const res = await getParents(bindcode)
      this.parentList = res.data
      this.isParentListEdit = []
      for (let index in this.parentList) {
        this.isParentListEdit.push(false)
      }
    },
    /***
     * 启用状态修改
     * @param row
     */
    async handleModifyStatus(row) {

      // console.log('switch===' + row.active)
      let words = ''
      let type = ''
      row.active = row.active == 0 ? 1 : 0
      // console.log('switch===' + row.active)
      let server = {}
      this.server_data_convert(row, server, 0)
      const { code } = await updateStudent(-1, server)
      if (code == '20000') {
        if (row.active == 0) {
          this.str_tableRowClassName = 'alive-row'
          words = '学生将无法使用此账号'
          type = 'warning'
        } else {
          this.str_tableRowClassName = ''
          words = '学生可以使用此账号'
          type = 'success'
        }

        this.$message({
          message: '操作成功:' + words,
          type: type
        })
      }

    },

    /***
     * 支付状态修改
     * @param row
     * @returns {Promise<void>}
     */
    async handlePayStatus(row) {

      let server = {}
      this.server_data_convert(row, server, 0)
      server.payStatus = server.payStatus == 0 ? 1 : 0
      const { code } = await updateStudent(row.key, server)
      const { data } = await updatePayStatus(row.bindcode, { pay_status: server.payStatus, expire: 99999999 })
      console.log('data==' + data)

      if (20000 == parseInt(code) && data.message == '编辑用户成功') {
        row.pay_status = server.payStatus
      }

      // for (let index = 0; index < this.temperList.length; index++) {
      //   if (this.temperList[index].key === this.temper.key) {
      //     this.temperList.splice(index, 1, Object.assign({}, this.temper))
      //     break
      //   }
      // }

    },

    getHeaderExcel(array, value) {

      let arr = []
      array.forEach(e => {
        if (e.checked) {
          arr.push(e[value])
        }
      })
      return arr

    },

    getValueExcel(array, value) {

      let arr = []
      array.forEach(e => {
        if (e.checked) {
          // if (e.label == '年级') {
          //   console.log('导出数据：' + e.label + '  ' + e[value])
          //
          //   arr.push(this.$global.GRADE_LOCAL[e[value]])
          //
          // } else if (e.label == '班级') {
          //   console.log('导出数据：' + e.label + '  ' + e[value])
          //
          //   arr.push(e[value] + '班')
          //
          // } else {
          arr.push(e[value])
          // }
        }
      })
      return arr

    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    },

    findObjByProp(pname, value, array) {
      return findObjByProp(pname, value, array)
    }

  }

}
</script>

<style scoped>
.filter-item {
  /*float: right;*/
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .alive-row {
  /*background: #dc707d;*/
  background: #DCDFE6;
}

/*.upload-demo {*/
/*  text-align: center;*/
/*  vertical-align: middle;*/
/*  margin-top: 0;*/
/*  width: 50%;*/
/*}*/


</style>
<style>
.el-table th {
  display: table-cell !important;
}


</style>
